/*
     File: Msg.m
 //  HelloWorld
 //
 //  Created by Martin Le C. on 6/7/09.
 //  Copyright 2009 __MyCompanyName__. All rights reserved.
 
 */

#import "Msg.h"
static sqlite3 *database = nil;
static sqlite3_stmt *deleteStmt = nil;
static sqlite3_stmt *addStmt = nil;
@implementation Msg
@synthesize pk, f, to , text;
+ (void) finalizeStatements {
	
	if(database) sqlite3_close(database);
	if(deleteStmt) sqlite3_finalize(deleteStmt);
	if(addStmt) sqlite3_finalize(addStmt);
}
- (id) initWithPrimaryKey:(NSInteger) primaryKey {
	
	[super init];
	pk = primaryKey;
	return self;
}

- (void) deleteMsg {
	
	if(deleteStmt == nil) {
		const char *sql = "DELETE FROM msg";
		NSLog(@"testing");
		if(sqlite3_prepare_v2(database, sql, -1, &deleteStmt, NULL) != SQLITE_OK) {
			NSLog(@"testing");
			NSAssert1(0, @"Error while creating delete statement. '%s'", sqlite3_errmsg(database));
		}
			
	}
	
	if (SQLITE_DONE != sqlite3_step(deleteStmt)) 
		NSAssert1(0, @"Error while deleting. '%s'", sqlite3_errmsg(database));
	
	sqlite3_reset(deleteStmt);
}

- (void) addMsg:(sqlite3 *)db {
	database = db;
	if(addStmt == nil) {
		NSLog(@"Error while creating add statement. '%s'", sqlite3_errmsg(database));
		//const char *sql = "insert into Coffee(CoffeeName, Price) Values(?, ?)";
		const char *sql = "INSERT INTO msg (f, t, text) VALUES (?, ?, ?)";
		if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK) {
			NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));
		}
	}
	sqlite3_bind_text(addStmt, 1, [f UTF8String], -1, SQLITE_TRANSIENT);
	sqlite3_bind_text(addStmt, 2, [to UTF8String], -1, SQLITE_TRANSIENT);
	sqlite3_bind_text(addStmt, 3, [text UTF8String], -1, SQLITE_TRANSIENT);
	
	if(SQLITE_DONE != sqlite3_step(addStmt))
		NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
	else
		//SQLite provides a method to get the last primary key inserted by using sqlite3_last_insert_rowid
		pk = sqlite3_last_insert_rowid(database);
	NSLog(@"%i", pk);
	//Reset the add statement.
	sqlite3_reset(addStmt);
}
- (void)dealloc {
    [f release];
	[to release];
    [text release];
	[super dealloc];
}
@end